package com.urtime.util;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.oro.text.regex.MalformedPatternException;import org.apache.oro.text.regex.Perl5Compiler;import org.apache.oro.text.regex.Perl5Matcher;public class Common {
	private static final String[] notes = {"notenum", "pokenum", "addfriendnum", "mtaginvitenum",
			"eventinvitenum", "myinvitenum"};
	private static final String[] acs = {"sendmail", "pm", "friend"};
	private static final char[] pregChars = {'.', '\\', '+', '*', '?', '[', '^', ']', '$', '(', ')', '{',
			'}', '=', '!', '<', '>', '|', ':'};
	private static final String randChars = "0123456789abcdefghigklmnopqrstuvtxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";
	private static Random random = new Random();
	private static Map<String, String[]> timeZoneIDs = new LinkedHashMap<String, String[]>(32);
	static {
		timeZoneIDs.put("-12", new String[] {"GMT-12:00", "(GMT -12:00) Eniwetok, Kwajalein"});
		timeZoneIDs.put("-11", new String[] {"GMT-11:00", "(GMT -11:00) Midway Island, Samoa"});
		timeZoneIDs.put("-10", new String[] {"GMT-10:00", "(GMT -10:00) Hawaii"});
		timeZoneIDs.put("-9", new String[] {"GMT-09:00", "(GMT -09:00) Alaska"});
		timeZoneIDs.put("-8", new String[] {"GMT-08:00",
				"(GMT -08:00) Pacific Time (US &amp; Canada), Tijuana"});
		timeZoneIDs.put("-7", new String[] {"GMT-07:00",
				"(GMT -07:00) Mountain Time (US &amp; Canada), Arizona"});
		timeZoneIDs.put("-6", new String[] {"GMT-06:00",
				"(GMT -06:00) Central Time (US &amp; Canada), Mexico City"});
		timeZoneIDs.put("-5", new String[] {"GMT-05:00",
				"(GMT -05:00) Eastern Time (US &amp; Canada), Bogota, Lima, Quito"});
		timeZoneIDs.put("-4", new String[] {"GMT-04:00",
				"(GMT -04:00) Atlantic Time (Canada), Caracas, La Paz"});
		timeZoneIDs.put("-3.5", new String[] {"GMT-03:30", "(GMT -03:30) Newfoundland"});
		timeZoneIDs.put("-3", new String[] {"GMT-03:00",
				"(GMT -03:00) Brassila, Buenos Aires, Georgetown, Falkland Is"});
		timeZoneIDs.put("-2", new String[] {"GMT-02:00",
				"(GMT -02:00) Mid-Atlantic, Ascension Is., St. Helena"});
		timeZoneIDs.put("-1", new String[] {"GMT-01:00", "(GMT -01:00) Azores, Cape Verde Islands"});
		timeZoneIDs.put("0", new String[] {"GMT",
				"(GMT) Casablanca, Dublin, Edinburgh, London, Lisbon, Monrovia"});
		timeZoneIDs.put("1", new String[] {"GMT+01:00",
				"(GMT +01:00) Amsterdam, Berlin, Brussels, Madrid, Paris, Rome"});
		timeZoneIDs.put("2", new String[] {"GMT+02:00",
				"(GMT +02:00) Cairo, Helsinki, Kaliningrad, South Africa"});
		timeZoneIDs.put("3", new String[] {"GMT+03:00", "(GMT +03:00) Baghdad, Riyadh, Moscow, Nairobi"});
		timeZoneIDs.put("3.5", new String[] {"GMT+03:30", "(GMT +03:30) Tehran"});
		timeZoneIDs.put("4", new String[] {"GMT+04:00", "(GMT +04:00) Abu Dhabi, Baku, Muscat, Tbilisi"});
		timeZoneIDs.put("4.5", new String[] {"GMT+04:30", "(GMT +04:30) Kabul"});
		timeZoneIDs.put("5", new String[] {"GMT+05:00",
				"(GMT +05:00) Ekaterinburg, Islamabad, Karachi, Tashkent"});
		timeZoneIDs
				.put("5.5", new String[] {"GMT+05:30", "(GMT +05:30) Bombay, Calcutta, Madras, New Delhi"});
		timeZoneIDs.put("5.75", new String[] {"GMT+05:45", "(GMT +05:45) Katmandu"});
		timeZoneIDs.put("6", new String[] {"GMT+06:00", "(GMT +06:00) Almaty, Colombo, Dhaka, Novosibirsk"});
		timeZoneIDs.put("6.5", new String[] {"GMT+06:30", "(GMT +06:30) Rangoon"});
		timeZoneIDs.put("7", new String[] {"GMT+07:00", "(GMT +07:00) Bangkok, Hanoi, Jakarta"});
		timeZoneIDs.put("8", new String[] {"GMT+08:00",
				"(GMT +08:00) Beijing, Hong Kong, Perth, Singapore, Taipei"});
		timeZoneIDs
				.put("9", new String[] {"GMT+09:00", "(GMT +09:00) Osaka, Sapporo, Seoul, Tokyo, Yakutsk"});
		timeZoneIDs.put("9.5", new String[] {"GMT+09:30", "(GMT +09:30) Adelaide, Darwin"});
		timeZoneIDs.put("10", new String[] {"GMT+10:00",
				"(GMT +10:00) Canberra, Guam, Melbourne, Sydney, Vladivostok"});
		timeZoneIDs.put("11", new String[] {"GMT+11:00",
				"(GMT +11:00) Magadan, New Caledonia, Solomon Islands"});
		timeZoneIDs.put("12", new String[] {"GMT+12:00",
				"(GMT +12:00) Auckland, Wellington, Fiji, Marshall Island"});
	}
	@SuppressWarnings("unchecked")
	public static boolean empty(Object obj) {
		if (obj == null) {
			return true;
		} else if (obj instanceof String && (obj.equals("") || obj.equals("0"))) {
			return true;
		} else if (obj instanceof Number && ((Number) obj).doubleValue() == 0) {
			return true;
		} else if (obj instanceof Boolean && !((Boolean) obj)) {
			return true;
		} else if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Map && ((Map) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Object[] && ((Object[]) obj).length == 0) {
			return true;
		}
		return false;
	}
	public static String trim(String text) {
		if (text == null) {
			return "";
		}
		return text.trim();
	}
	public static boolean in_array(Object source, Object ext) {
		return in_array(source, ext, false);
	}
	public static boolean in_array(Object source, Object ext, boolean strict) {
		if (source == null || ext == null) {
			return false;
		}
		if (source instanceof Collection) {
			for (Object s : (Collection) source) {
				if (s.toString().equals(ext.toString())) {
					if (strict) {
						if ((s.getClass().getName().equals(ext.getClass().getName()))) {
							return true;
						}
					} else {
						return true;
					}
				}
			}
		} else {
			for (Object s : (Object[]) source) {
				if (s.toString().equals(ext.toString())) {
					if (strict) {
						if ((s.getClass().getName().equals(ext.getClass().getName()))) {
							return true;
						}
					} else {
						return true;
					}
				}
			}
		}
		return false;
	}
	public static String urlEncode(String s) {
		return urlEncode(s, UrTimeServerConfig.CHARSET);
	}
	public static String urlEncode(String s, String enc) {
		if (!empty(s)) {
			try {
				return URLEncoder.encode(s, enc);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return s;
	}
	public static String urlDecode(String s) {
		return urlDecode(s, UrTimeServerConfig.CHARSET);
	}
	public static String urlDecode(String s, String enc) {
		if (!empty(s)) {
			try {
				return URLDecoder.decode(s, enc);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return s;
	}
	public static int rand(int max) {
		return rand(0, max);
	}
	public static int rand(int min, int max) {
		if (min < max) {
			return random.nextInt(max - min + 1) + min;
		} else {
			return min;
		}
	}
	public static String md5(String arg0) {
		return Md5Util.encode(arg0);
	}
	@SuppressWarnings("unchecked")
	public static String implode(Object data, String separator) {
		if (data == null) {
			return "";
		}
		StringBuffer out = new StringBuffer();
		if (data instanceof Object[]) {
			boolean flag = false;
			for (Object obj : (Object[]) data) {
				if (flag) {
					out.append(separator);
				} else {
					flag = true;
				}
				out.append(obj);
			}
		} else if (data instanceof Map) {
			Map temp = (Map) data;
			Set<Object> keys = temp.keySet();
			boolean flag = false;
			for (Object key : keys) {
				if (flag) {
					out.append(separator);
				} else {
					flag = true;
				}
				out.append(temp.get(key));
			}
		} else if (data instanceof Collection) {
			boolean flag = false;
			for (Object obj : (Collection) data) {
				if (flag) {
					out.append(separator);
				} else {
					flag = true;
				}
				out.append(obj);
			}
		} else {
			return data.toString();
		}
		return out.toString();
	}
	public static String sImplode(Object ids) {
		return "'" + implode(ids, "','") + "'";
	}
	public static int range(Object value, int max, int min) {
		if (value instanceof String) {
			return Math.min(max, Math.max(intval((String) value), min));
		} else {
			return Math.min(max, Math.max((Integer) value, min));
		}
	}
	public static int intval(String s) {
		return intval(s, 10);
	}
	public static int intval(String s, int radix) {
		if (s == null || s.length() == 0) {
			return 0;
		}
		if (radix == 0) {
			radix = 10;
		} else if (radix < Character.MIN_RADIX) {
			return 0;
		} else if (radix > Character.MAX_RADIX) {
			return 0;
		}
		int result = 0;
		int i = 0, max = s.length();
		int limit;
		int multmin;
		int digit;
		boolean negative = false;
		if (s.charAt(0) == '-') {
			negative = true;
			limit = Integer.MIN_VALUE;
			i++;
		} else {
			limit = -Integer.MAX_VALUE;
		}
		if (i < max) {
			digit = Character.digit(s.charAt(i++), radix);
			if (digit < 0) {
				return 0;
			} else {
				result = -digit;
			}
		}
		multmin = limit / radix;
		while (i < max) {
			digit = Character.digit(s.charAt(i++), radix);
			if (digit < 0) {
				break;
			}
			if (result < multmin) {
				result = limit;
				break;
			}
			result *= radix;
			if (result < limit + digit) {
				result = limit;
				break;
			}
			result -= digit;
		}
		if (negative) {
			if (i > 1) {
				return result;
			} else {
				return 0;
			}
		} else {
			return -result;
		}
	}
	public static Map<String, String[]> getTimeZoneIDs() {
		return timeZoneIDs;
	}
	public static int time() {
		return (int) (System.currentTimeMillis() / 1000);
	}
	public static SimpleDateFormat getSimpleDateFormat(String format, String timeoffset) {
		SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
		sdf.setTimeZone(TimeZone.getTimeZone(timeZoneIDs.get(timeoffset)[0]));
		return sdf;
	}
	public static String gmdate(SimpleDateFormat sdf, int timestamp) {
		return sdf.format(timestamp * 1000l);
	}
	public static String gmdate(String format, int timestamp, String timeoffset) {
		return getSimpleDateFormat(format, timeoffset).format(timestamp * 1000l);
	}

	public static boolean matches(String content, String regex) {
		boolean flag = false;
		try {
			flag = new Perl5Matcher().contains(content, new Perl5Compiler().compile(regex));
		} catch (MalformedPatternException e) {
			e.printStackTrace();
		}
		return flag;
	}
	public static String getRandStr(int length, boolean isOnlyNum) {
		int size = isOnlyNum ? 10 : 62;
		StringBuffer hash = new StringBuffer(length);
		for (int i = 0; i < length; i++) {
			hash.append(randChars.charAt(random.nextInt(size)));
		}
		return hash.toString();
	}
	public static String stripTags(String content) {
		return content == null ? "" : content.replaceAll("<[\\s\\S]*?>", "");
	}
	public static String htmlSpecialChars(String string) {
		return htmlSpecialChars(string, 1);
	}
	public static String htmlSpecialChars(String text, int quotestyle) {
		if (text == null || text.equals("")) {
			return "";
		}
		StringBuffer sb = new StringBuffer(text.length() * 2);
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			switch (character) {
				case '&':
					sb.append("&amp;");
					break;
				case '<':
					sb.append("&lt;");
					break;
				case '>':
					sb.append("&gt;");
					break;
				case '"':
					if (quotestyle == 1 || quotestyle == 2) {
						sb.append("&quot;");
					} else {
						sb.append(character);
					}
					break;
				case '\'':
					if (quotestyle == 2) {
						sb.append("&#039;");
					} else {
						sb.append(character);
					}
					break;
				default:
					sb.append(character);
					break;
			}
			character = iterator.next();
		}
		return sb.toString();
	}
	public static String addSlashes(String text) {
		if (text == null || text.equals("")) {
			return "";
		}
		StringBuffer sb = new StringBuffer(text.length() * 2);
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			switch (character) {
				case '\'':
				case '"':
				case '\\':
					sb.append("\\");
				default:
					sb.append(character);
					break;
			}
			character = iterator.next();
		}
		return sb.toString();
	}
	public static String addCSlashes(String text, char[] characters) {
		if (text == null || text.equals("")) {
			return "";
		}
		StringBuffer sb = new StringBuffer(text.length() * 2);
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			for (char c : characters) {
				if (character == c) {
					sb.append("\\");
					break;
				}
			}
			sb.append(character);
			character = iterator.next();
		}
		return sb.toString();
	}
	public static String stripSlashes(String text) {
		if (text == null || text.equals("")) {
			return "";
		}
		StringBuffer sb = new StringBuffer(text.length());
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			switch (character) {
				case '\'':
					sb.append("'");
					break;
				case '"':
					sb.append('"');
					break;
				case '\\':
					sb.append(iterator.next());
					break;
				default:
					sb.append(character);
					break;
			}
			character = iterator.next();
		}
		return sb.toString();
	}
	public static String stripCSlashes(String text) {
		if (text == null || text.equals("")) {
			return "";
		}
		StringBuffer sb = new StringBuffer(text.length());
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		boolean flag = true;
		while (character != StringCharacterIterator.DONE) {
			if (character == '\\' && flag) {
				flag = false;
			} else {
				flag = true;
				sb.append(character);
			}
			character = iterator.next();
		}
		return sb.toString();
	}
	@SuppressWarnings("unchecked")
	public static Object sAddSlashes(Object obj) {
		if (obj instanceof String) {
			return addSlashes((String) obj);
		} else if (obj instanceof Map) {
			Map temp = (Map) obj;
			Set<Object> keys = temp.keySet();
			for (Object key : keys) {
				temp.put(key, sAddSlashes(temp.get(key)));
			}
			return temp;
		} else if (obj instanceof List) {
			List temp = new ArrayList();
			for (Object str : (List) obj) {
				temp.add(sAddSlashes(str));
			}
			return temp;
		} else if (obj instanceof Object[]) {
			Object[] temp = (Object[]) obj;
			for (int i = 0; i < temp.length; i++) {
				temp[i] = sAddSlashes(temp[i]);
			}
			return temp;
		} else {
			return obj;
		}
	}
	@SuppressWarnings("unchecked")
	public static Object sStripSlashes(Object obj) {
		if (obj instanceof String) {
			return stripSlashes((String) obj);
		} else if (obj instanceof Map) {
			Map temp = (Map) obj;
			Set<Object> keys = temp.keySet();
			for (Object key : keys) {
				temp.put(key, sStripSlashes(temp.get(key)));
			}
			return temp;
		} else if (obj instanceof List) {
			List temp = new ArrayList();
			for (Object str : (List) obj) {
				temp.add(sStripSlashes(str));
			}
			return temp;
		} else if (obj instanceof Set) {
			Set temp = new HashSet();
			for (Object str : (Set) obj) {
				temp.add(sStripSlashes(str));
			}
			return temp;
		} else if (obj instanceof Object[]) {
			Object[] temp = (Object[]) obj;
			for (int i = 0; i < temp.length; i++) {
				temp[i] = sStripSlashes(temp[i]);
			}
			return temp;
		} else {
			return obj;
		}
	}
	@SuppressWarnings("unchecked")
	public static Object sHtmlSpecialChars(Object obj) {
		if (obj instanceof String) {
			return htmlSpecialChars((String) obj).replaceAll(
					"&amp;((#(\\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)", "&$1");
		} else if (obj instanceof Map) {
			Map temp = (Map) obj;
			Set<Object> keys = temp.keySet();
			for (Object key : keys) {
				temp.put(key, sHtmlSpecialChars(temp.get(key)));
			}
			return temp;
		} else if (obj instanceof List) {
			List temp = new ArrayList();
			for (Object str : (List) obj) {
				temp.add(sHtmlSpecialChars(str));
			}
			return temp;
		} else if (obj instanceof Object[]) {
			Object[] temp = (Object[]) obj;
			for (int i = 0; i < temp.length; i++) {
				temp[i] = sHtmlSpecialChars(temp[i]);
			}
			return temp;
		} else {
			return obj;
		}
	}
	public static boolean isArray(Object obj) {
		if (obj instanceof Object[]) {
			return true;
		} else if (obj instanceof Collection) {
			return true;
		} else if (obj instanceof Map) {
			return true;
		} else {
			return false;
		}
	}
	public static int strlen(String text) {
		return strlen(text, UrTimeServerConfig.CHARSET);
	}
	public static int strlen(String text, String charsetName) {
		if (text == null || text.length() == 0) {
			return 0;
		}
		int length = 0;
		try {
			length = text.getBytes(charsetName).length;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return length;
	}
	public static String cutstr(String text, int length) {
		return cutstr(text, length, " ...");
	}
	public static String cutstr(String text, int length, String dot) {
		int strBLen = strlen(text);
		if (strBLen <= length) {
			return text;
		}
		int temp = 0;
		StringBuffer sb = new StringBuffer(length);
		char[] ch = text.toCharArray();
		for (char c : ch) {
			sb.append(c);
			if (c > 256) {
				temp += 2;
			} else {
				temp += 1;
			}
			if (temp >= length) {
				if (dot != null) {
					sb.append(dot);
				}
				break;
			}
		}
		return sb.toString();
	}
	public static boolean isNumeric(Object obj) {
		if (obj instanceof String && !obj.equals("")) {
			String temp = (String) obj;
			if (temp.endsWith("d") || temp.endsWith("f")) {
				return false;
			} else {
				try {
					Double.parseDouble(temp);
				} catch (Exception e) {
					return false;
				}
			}
			return true;
		} else if (obj instanceof Number) {
			return true;
		} else {
			return false;
		}
	}
	public static boolean isEmail(String email) {
		return Common.strlen(email) > 6 && email.matches("^[\\w\\-\\.]+@[\\w\\-\\.]+(\\.\\w+)+$");
	}
	public static String pregQuote(String text, char... delimiter) {
		StringBuffer sb = new StringBuffer(text.length() * 2);
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			boolean flag = false;
			for (char c : pregChars) {
				if (character == c) {
					flag = true;
					break;
				}
			}
			if (!flag && delimiter != null) {
				for (char d : delimiter) {
					if (character == d) {
						flag = true;
						break;
					}
				}
			}
			if (flag) {
				sb.append('\\');
			}
			sb.append(character);
			character = iterator.next();
		}
		return sb.toString();
	}
	public static String nl2br(String text) {
		if (text == null || text.length() == 0) {
			return text;
		}
		StringBuffer sb = new StringBuffer(text.length() * 2);
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			switch (character) {
				case '\r':
					sb.append("<br/>");
					sb.append(character);
					character = iterator.next();
					if (character == '\n') {
						character = iterator.next();
					}
					break;
				case '\n':
					sb.append("<br/>");
					sb.append(character);
					character = iterator.next();
					if (character == '\r') {
						sb.append(character);
						character = iterator.next();
					}
					break;
				default:
					sb.append(character);
					character = iterator.next();
					break;
			}
		}
		return sb.toString();
	}
	public static String sprintf(String format, double number) {
		return new DecimalFormat(format).format(number);
	}
	public static String formatSize(long dataSize) {
		dataSize = Math.abs(dataSize);
		if (dataSize >= 1099511627776d) {
			return (Math.round(dataSize / 1099511627776d * 100) / 100d) + " TB";
		} else if (dataSize >= 1073741824) {
			return (Math.round(dataSize / 1073741824d * 100) / 100d) + " GB";
		} else if (dataSize >= 1048576) {
			return (Math.round(dataSize / 1048576d * 100) / 100d) + " MB";
		} else if (dataSize >= 1024) {
			return (Math.round(dataSize / 1024d * 100) / 100d) + " KB";
		} else if (dataSize > 0) {
			return dataSize + " B ";
		} else {
			return "   0 B ";
		}
	}	

}